package com.example.service;

import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class MessageService {
    private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();
    private final Map<String, String> latestMessages = new ConcurrentHashMap<>();
    private final Map<String, String> lastSentMessages = new ConcurrentHashMap<>();

    public SseEmitter createEmitter(String clientId) {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
        
        emitter.onCompletion(() -> removeClient(clientId));
        emitter.onTimeout(() -> removeClient(clientId));
        
        emitters.put(clientId, emitter);
        
        try {
            emitter.send(SseEmitter.event()
                    .name("INIT")
                    .data("Connected with ID: " + clientId));
        } catch (IOException e) {
            emitter.completeWithError(e);
        }
        return emitter;
    }

    public void sendMessage(String clientId, String message) {
        if (emitters.containsKey(clientId)) {
            latestMessages.put(clientId, message);
        }
    }

    public void broadcast(String message) {
        emitters.keySet().forEach(clientId -> 
            latestMessages.put(clientId, message)
        );
    }

    public void processAndSendMessages() {
        latestMessages.forEach((clientId, message) -> {
            SseEmitter emitter = emitters.get(clientId);
            if (emitter != null) {
                String lastSentMessage = lastSentMessages.get(clientId);
                if (!message.equals(lastSentMessage)) {
                    try {
                        emitter.send(SseEmitter.event()
                                .name("MESSAGE")
                                .data(message));
                        lastSentMessages.put(clientId, message);
                    } catch (IOException e) {
                        removeClient(clientId);
                    }
                }
            }
        });
    }

    private void removeClient(String clientId) {
        emitters.remove(clientId);
        latestMessages.remove(clientId);
        lastSentMessages.remove(clientId);
    }
}
